﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


public static class DownloadMonitor
{
    public enum ReportId
    {
        //下载耗时上报调试
        RequestUpdateApi = 10000,
        CopyStreamingAsset = 10001,
        DownloadClientArgs = 10002,

        DownloadVersionFile = 10003,
        DownloadBundleInfo = 10004,
        DownloadBundleInfoZip = 10005,
        PreDownloadUpdateTime = 10006,
        FullDownloadUpdateTime = 10007,
        CheckCDNDns = 11000,
        CheckApiDns = 11001,
        DnsError = 11002,
        DownloadSpeed=11003,
        CDNPing=11004,
    }


    public static bool Enable = true;

    static Queue<Stopwatch> WatcherPool = new Queue<Stopwatch>(10);
    static Dictionary<int, Stopwatch> runningWatcher = new Dictionary<int, Stopwatch>();
    static Stopwatch GetWatcher()
    {
        if (WatcherPool.Count > 0) {
            Stopwatch w = WatcherPool.Dequeue();
            w.Reset();
            w.Start();
            return w;
        }
        else
        {
            return new Stopwatch();
        }

    }

    static void ReleaseWatcher(Stopwatch w)
    {
        w.Stop();
        if (WatcherPool.Count < 10)
        {
            WatcherPool.Enqueue(w);
        }
    }

    public static void CleanUp()
    {
        foreach (Stopwatch sw in runningWatcher.Values)
        {
            sw.Stop();
        }
        runningWatcher.Clear();
        WatcherPool.Clear();
    }

    public static void Watch(int id)
    {
        //if (Enable)
        //{
        //    if (runningWatcher.ContainsKey(id))
        //    {
        //        UnityEngine.Debug.LogError($"当前已有监控 {id}");
        //    }
        //    else
        //    {
        //        runningWatcher[id] = GetWatcher();
        //    }
        //}
    }

    public static void AutoReport(int id)
    {
        if (Enable)
        {
            if (runningWatcher.TryGetValue(id, out Stopwatch w))
            {
                TimeSpan ts = w.Elapsed;
                runningWatcher.Remove(id);
                ReleaseWatcher(w);
            }
        }
    }

    public static void Abort(int id)
    {
        if (runningWatcher.TryGetValue(id, out Stopwatch w))
        {
            runningWatcher.Remove(id);
            ReleaseWatcher(w);
        }
    }



    public static void start(int id)
    {
        if (runningWatcher.ContainsKey(id))
        {
            UnityEngine.Debug.LogError($"当前已有监控 {id}");
        }
        else
        {
            runningWatcher[id] = GetWatcher();
        }
    }
    public static TimeSpan Stop(int id)
    {
        if (runningWatcher.TryGetValue(id, out Stopwatch w))
        {
            TimeSpan ts = w.Elapsed;
            runningWatcher.Remove(id);
            ReleaseWatcher(w);
            return ts;
        }
        else
            return TimeSpan.FromTicks(0);
    }

}

